import { IUser, Relevance, Connect } from '../types'
import { ObjectId } from 'mongodb'
import { stats } from '../stats'

import * as db from '../db'
import * as crypto from 'crypto'

// 增加减少数量
export async function changenum(bookId: string, obj: Object) {
  await db.booksCollection.findOneAndUpdate({ _id: new ObjectId(bookId) }, obj)
}

// 加密
export function sha(str: string) {
  const hash = crypto.createHash('sha1')
  hash.update(str)
  return hash.digest('hex')
}

// stinrg[] -> ObjectId[]
export function stoObjId(ids: string[]) {
  const others: ObjectId[] = []
  ids.forEach(item => {
    others.push(new ObjectId(item))
  })
  return others
}

// 检查是否店点赞收藏
export async function checkSome(
  userId: ObjectId,
  destId: ObjectId,
  type: Relevance
) {
  const mid = await db.connectCollection.findOne({
    userId,
    destId,
    type: type
  })
  return mid
}

// 添加点赞 收藏 关注等等
export async function addSome(
  userId: ObjectId,
  destId: ObjectId,
  type: Relevance
) {
  await db.connectCollection.insertOne({
    _id: null,
    userId,
    destId,
    time: Date.now(),
    type: type
  })
}

// 取消点赞 收藏 关注 订单 等等
export async function removeSome(
  userId: ObjectId,
  destId: ObjectId,
  type: Relevance
) {
  const mid = await db.connectCollection.findOne({
    userId,
    destId,
    type: type
  })
  if (!mid) throw stats.ErrNotFound
  await db.connectCollection.deleteOne({ _id: mid._id })
}

// 查询 中间连接表
export async function dealmid(
  userId: ObjectId,
  type: Relevance,
  skip: number,
  limit: number
) {
  const mids = await db.connectCollection
    .aggregate([
      { $match: { userId, type } },
      { $skip: skip },
      { $limit: limit },
      {
        $project: { destId: 1 }
      }
    ])
    .toArray()
  const destIds = mids.map(m => m.destId)
  const total = await db.connectCollection.find({ userId, type }).count()
  return { destIds, total }
}
// 查询全部 中间连接表
export async function dealAllmid(
  userId: ObjectId,
  type: Relevance
) {
  const mids = await db.connectCollection
    .aggregate([
      { $match: { userId, type } },
      {
        $project: { destId: 1 }
      }
    ])
    .toArray()
  const destIds = mids.map(m => m.destId)
  const total = await db.connectCollection.find({ userId, type }).count()
  return { destIds, total }
}

// 通过购物车的中间表id查到书籍id
export async function cTob(cartIds: ObjectId[]) {
  const list = await db.connectCollection
    .find(
      { _id: { $in: cartIds } },
      {
        projection: { destId: 1 }
      }
    )
    .toArray()
  return list.map(item => item.destId)
}

// 修改库存
export async function Stock(mids: ObjectId[], num: number) {
  const books = await db.connectCollection
    .aggregate([
      { $match: { _id: { $in: mids } } },
      {
        $lookup: {
          from: 'books',
          localField: 'destId',
          foreignField: '_id',
          as: 'book'
        }
      },
      { $unwind: '$book' },
      {
        $project: {
          indexs: 1,
          book: {
            _id: 1
          }
        }
      }
    ])
    .toArray()
  books.forEach(async item => {
    const shu = await db.booksCollection.findOne({ _id: item.book._id })
    const obj: { bookname: string; price: number; stock: number }[] = []
    shu.books.forEach((s, i) => {
      if (item.indexs.includes(i)) {
        obj.push({ ...s, stock: s.stock + num })
      } else obj.push(s)
    })
    await db.booksCollection.findOneAndUpdate(
      { _id: item.book._id },
      { $set: { books: obj } }
    )
  })
}
